<template>
    <el-dialog v-model="show" :title="title" width="50%" align-center @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="ruleForm.type" placeholder="请选择类型" style="width: 200px;">
                            <el-option v-for="item in props.initList?.product_style_type" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请输入名称" style="width: 200px;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="配件模型" prop="fileList">
                        <el-upload ref="upload" v-model:file-list="ruleForm.fileList"
                            style="display: flex; align-items: center;" :action="uploadImgUrl" :headers="headers"
                            :limit="1" :on-success="handleUploadSuccess" :on-exceed="handleExceed">
                            <template #trigger>
                                <el-button type="primary">上传模型</el-button>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="配件展示图" prop="imageUrl">
                        <el-upload ref="designSketchRef" :show-file-list="false" drag :action="uploadImgUrl"
                            :headers="headers" multiple :auto-upload="true" :on-success="handleDesignSketchSuccess"
                            :before-upload="beforedeSignSketchUpload">
                            <img style="height: 100px;" v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle type="1" icon="PictureFilled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-for="(item, index) in componentTypeList" :key="index">
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <el-form-item :label="item.label">
                                <el-select multiple v-model="item.componentId" :placeholder="`请选择${item.label}`"
                                    style="width: 180px;">
                                    <el-option v-for="dick in props.initList?.styleList[item.value]" :key="dick.id"
                                        :label="dick.name" :value="dick.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否移除">
                                <el-checkbox v-model="item.removeFlag" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="替换部件名称">
                                <el-input v-model="item.replaceComponentName" placeholder="请输入替换部件名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="替换部件定位点名称">
                                <el-input v-model="item.replaceLocationName" placeholder="请输入替换部件定位点名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="替换部件偏移位置">
                                <el-input v-model="item.location" placeholder="参考x,y,z格式" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" v-loading="loading" @click="handleSubmit(ruleFormRef)">{{ btnTitle }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { addStyle, updateStyle } from '@/api/portfolioManagement/index'
import { globalHeaders } from "@/utils/request";
import uploadStyle from '@/components/uploadStyle.vue'

import { genFileId, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const componentTypeList: any = ref([])
const btnTitle = ref('新 增');
const title = ref('新增配置信息')
watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {

        if (props.initList?.id) {
            title.value = '修改配置信息'
            btnTitle.value = '修 改'

            try {
                ruleForm.type = props.initList?.detailsObj?.type
                ruleForm.imageUrl = props.initList?.detailsObj?.imageUrl
                ruleForm.name = props.initList?.detailsObj?.name
                ruleForm.fileList = [{
                    name: '模型',
                    url: props.initList?.detailsObj?.modelUrl
                }]
                let temporaryList: any[] = []
                if (props.initList?.component_type.length > 0 && props.initList?.detailsObj?.joinComponents.length > 0) {
                    props.initList?.detailsObj?.joinComponents.forEach((dick: any) => {
                        props.initList?.component_type.map((item: any) => {
                            let listObj = {}
                            if (dick.componentType == item.value) {
                                listObj = {
                                    label: item.label,
                                    value: item.value,
                                    removeFlag: dick.removeFlag == 1 ? true : false,
                                    location: dick.location,
                                    replaceComponentName: dick.replaceComponentName,
                                    replaceLocationName: dick.replaceLocationName,
                                    componentId: dick.componentIds
                                }

                                temporaryList.push(listObj)
                            }
                        })
                    })
                }

                componentTypeList.value = props.initList?.component_type.map((item: any) => {
                    if (!temporaryList.some((element: any) => element.value == item.value)) {
                        return {
                            label: item.label,
                            value: item.value,
                            removeFlag: false,
                            location: '',
                            replaceComponentName: '',
                            replaceLocationName: '',
                            componentId: []
                        }
                    } else {
                        return temporaryList.filter((element: any) => element.value == item.value)[0]
                    }
                })
            } catch (error) {
                console.log(error);
            }
        } else {
            title.value = '新增配置信息'
            btnTitle.value = '新 增'
            if (props.initList?.component_type.length > 0) {
                componentTypeList.value = props.initList?.component_type.map((item: any) => {
                    return {
                        label: item.label,
                        value: item.value,
                        removeFlag: false,
                        location: '',
                        replaceComponentName: '',
                        replaceLocationName: '',
                        componentId: []
                    }
                })
            }
        }
    }
}, { deep: true });

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<any>({
    type: '',
    name: '',
    fileList: [],
    imageUrl: ''
})
const fileTypes = ['image/png', 'image/jpeg']

const rules = reactive<any>({
    type: [
        { required: true, message: '请选择类型', trigger: ['change', 'blur'] },
    ],
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    fileList: [
        { required: true, message: '请上传模型', trigger: ['change', 'blur'] },
    ],
    imageUrl: [
        { required: true, message: '请上传展示图', trigger: ['change', 'blur'] },
    ],
})

const upload = ref<UploadInstance>()
const loading = ref(false)
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let quert = {
                ...ruleForm,
                modelUrl: ruleForm.fileList.length != 0 ? ruleForm.fileList[0].url : '',
                joinComponents: componentTypeList.value.map((item: any) => {
                    return {
                        replaceLocationName: item.replaceLocationName,
                        replaceComponentName: item.replaceComponentName,
                        location: item.location,
                        componentId: item.componentId,
                        removeFlag: item.removeFlag ? 1 : 0
                    }
                }),
            }

            if (props.initList?.id) {
                quert.id = props.initList?.id
                try {
                    loading.value = true;
                    await updateStyle(quert)
                    proxy?.$modal.msgSuccess('修改成功');
                    emits('submit', true);
                    loading.value = false;

                    handleClose();
                } catch (error) {
                    loading.value = false;
                }
            } else {
                try {
                    loading.value = true;
                    await addStyle(quert)
                    proxy?.$modal.msgSuccess('操作成功');
                    emits('submit', true);
                    loading.value = false;

                    handleClose();
                } catch (error) {
                    loading.value = false;
                }
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 上传模型 就上传一个 后续上传直接替换掉
 */
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
/**
 * 上传模型成功
 */
const handleUploadSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.fileList = [{
        name: response.data.fileName,
        url: response.data.url
    }]
};

/**
 * 上传配件展示图格式的判定
 */
const beforedeSignSketchUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile)
    if (!fileTypes.includes(rawFile.type)) {
        ElMessage.error('请上传jpg/png格式的图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

/**
 * 上传配件展示图 成功回调
 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    ruleForm.imageUrl = response.data.url
};
const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.exhibition {
    width: 100%;
    max-height: 400px;
    overflow-y: auto;
    padding: 5px;

    .colourContainer {
        cursor: pointer;

        &_list {
            display: flex;
            align-items: center;
            height: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        &_item {
            margin-right: 10px;
            width: 100px;

            .el-image {
                border-radius: 12px;
            }

            &_name {
                text-align: center;
                width: 100%;
            }
        }

    }

    &_container {
        margin-top: 10px;
        display: flex;

        >div {
            flex: 1;
        }
    }
}



::v-deep .el-upload-list {
    margin: 0;
    width: 100px;
}

::v-deep .el-upload-list__item {
    margin-bottom: 0;
}

::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 100px !important;
    width: 260px;
}

::v-deep .el-divider--horizontal {
    margin: 12px 0;
}
</style>